package com.bookstore.bookfactory;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.Element;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Admin on 9/12 0012.
 */
public class BeanFactory {
    public static Map<String, Object> beans = new HashMap<>();


    public static void main(String[] args) throws DocumentException,
            IllegalAccessException, InstantiationException, ClassNotFoundException,
            NoSuchMethodException, NoSuchFieldException, InvocationTargetException, IntrospectionException {
        initXml();
    }

    static {
        try {
            initXml();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void initXml() throws DocumentException, ClassNotFoundException,
            IllegalAccessException, InstantiationException, NoSuchFieldException,
            NoSuchMethodException, InvocationTargetException, IntrospectionException {

        SAXReader reader = new SAXReader();
        Document doc = reader.read(BeanFactory.class.getClassLoader().getResourceAsStream("bookstore.xml"));
        Element root = doc.getRootElement();
        //获取根标签
        List<Element> bs = root.elements();
        for (Element bean : bs) {
            //获取bean 标签的id和 class 属性值
            String id = bean.attributeValue("id");
            String className = bean.attributeValue("class");
            //根据class全类名创建类并实例化一个实例;
            Class clazz = Class.forName(className);
            Object obj = clazz.newInstance();
            //将这个实例放入map中
            beans.put(id, obj);
            //然后再遍历Bean标签中的内容;
            List<Element> properties = bean.elements();
            for (Element property : properties) {
                String name = property.attributeValue("name");
                String ref = property.attributeValue("ref");
                System.out.println(name);
//                PropertyDescriptor pd = new PropertyDescriptor(name, clazz);
//                pd.getWriteMethod().invoke(obj, beans.get(ref));
                Method method = clazz.getMethod("set" + name.substring(0, 1).toUpperCase() + name.substring(1),
                        clazz.getDeclaredField(name).getType());
                method.invoke(obj, beans.get(ref));

            }
        }
    }

    public static Object getBean(String str) {
        return beans.get(str);
    }

}
